package com.device.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.StandardCharsets;

@Service
public class DatabaseInitService implements CommandLineRunner {

    private static final Logger log = LoggerFactory.getLogger(DatabaseInitService.class);

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public void run(String... args) throws Exception {
        try {
            log.info("开始执行数据库迁移脚本...");
            executeMigrationScript();
            log.info("数据库迁移脚本执行完成");
        } catch (Exception e) {
            log.error("执行数据库迁移脚本时出错: {}", e.getMessage(), e);
            // 不抛出异常，让应用继续启动
        }
    }

    private void executeMigrationScript() {
        try {
            // 读取迁移脚本
            String migrationScript = readResourceFile("db_migration.sql");
            if (migrationScript != null && !migrationScript.trim().isEmpty()) {
                // 按分号分割SQL语句
                String[] sqlStatements = migrationScript.split(";");
                
                // 执行每条SQL语句
                for (String sql : sqlStatements) {
                    if (sql != null && !sql.trim().isEmpty()) {
                        try {
                            log.info("执行SQL: {}", sql.trim());
                            jdbcTemplate.execute(sql.trim());
                        } catch (Exception e) {
                            log.error("执行SQL语句时出错: {}", e.getMessage(), e);
                            // 继续执行下一条语句
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error("读取或执行迁移脚本时出错: {}", e.getMessage(), e);
        }
    }

    private String readResourceFile(String resourcePath) {
        try {
            ClassPathResource resource = new ClassPathResource(resourcePath);
            if (!resource.exists()) {
                log.warn("资源文件不存在: {}", resourcePath);
                return null;
            }
            
            try (Reader reader = new InputStreamReader(resource.getInputStream(), StandardCharsets.UTF_8)) {
                return FileCopyUtils.copyToString(reader);
            }
        } catch (IOException e) {
            log.error("读取资源文件时出错: {}", e.getMessage(), e);
            return null;
        }
    }
} 